#include <iostream>
#include "sqlite3.h"

#include "DRCDB.hpp"
#include "BusinessLogic.hpp"
#include "User.hpp"

using namespace std;

DRCDB::DRCDB(string filename)
{
	database = NULL;
	if (sqlite3_open(filename.c_str(), &database) == SQLITE_OK);
}

DRCDB::~DRCDB()
{
	sqlite3_close(database);
}


vector<vector<string> > DRCDB::query(sqlite3_stmt *statement)
{
	vector<vector<string> > results;

	int cols = sqlite3_column_count(statement);
	int result = 0;
	while(true)
	{
		result = sqlite3_step(statement);
		
		if(result == SQLITE_ROW)
		{
			vector<string> values;
			for(int col = 0; col < cols; col++)
			{
				string val;
				char *ptr = (char*)sqlite3_column_text(statement, col);
				val = ptr ? ptr : "<NULL>";
				values.push_back(val);
			}
			results.push_back(values);
		}
		else
		{
			break;   
		}
	}
   
	sqlite3_finalize(statement);
	
	string error = sqlite3_errmsg(database);
	if(error != "not an error") cout << "Error executing query" << error << endl;
	
	return results;  
}


enum LoginStatus DRCDB::login(User *user)
{
	string q = "SELECT UserName, UserPassword FROM Users WHERE UserName = ?;";
	
	sqlite3_stmt *statement = 0;
	if ( sqlite3_prepare_v2(this->database, q.c_str(), -1, &statement, 0) == SQLITE_OK )
	{
		string name = user->getUsername();
		sqlite3_bind_text(statement, 1, name.c_str(), name.size(), 0);
		vector<vector<string> > result = query(statement);

		if ( result.size() == 0 ) return LoginInvalidUser;

		for(vector<vector<string> >::iterator it = result.begin(); it < result.end(); ++it)
		{
			vector<string> row = *it;
			if ( row[1] != user->getPassword() ) return LoginInvalidPassword;
		}

		return LoginSuccess;
	}
	
	return LoginFailure;
}
